home *** CD-ROM | disk | FTP | other *** search
/ Ian & Stuart's Australian Mac 1993 September / September 93.iso / Archives / Applications / Calculators / NumberCrunch 1.41 / Number Crunch II Demo / Library Routines / Text Examples / Miscellaneous Routines < prev    next >
Encoding:
Text File  |  1992-10-06  |  11.4 KB  |  342 lines  |  [TEXT/NCII]

  1. ####################################
  2. #  Miscellaneous Routines
  3. #
  4. # These routines don't use any xCOD's, just NCII's built-in
  5. #  programming language.  
  6. #
  7. #   Truncate(x) = Int(x*(1+1e-19) - .5) # Returns integer <= x.;
  8. #   FractionalPart(x) = x - Truncate(x)# Returns fractional part of x>0.;
  9. #   Round(x, DecimalDigits) =  int(x*10^DecimalDigits)/10^DecimalDigits # rounds off x.;
  10. #   Mod(a,b) = a - b*Truncate(a/b) # Returns a mod b.;
  11. #   function IsEven(n) # Returns 1 if n is even, 0 if odd.
  12. #   Length(V) = sqrt(V•V) # length of a vector. ;
  13. #  AngleBetween(V,W) = acos( V•W /length(V) /length(W) ) # angle from vector V to W, in radians.;
  14. #   function Cross3D(X,Y)  # Returns the 3D cross product of two 3D vectors x,y.
  15. #   Hermitian(theMat) = Transpose(theMat†);
  16. #   Commutator(a,b) = a•b - b•a;
  17. #   function Trace(theMatrix) # Returns the sum of the diagonal elements of a matrix.
  18. #
  19. #   Differentiate(f,x,dx) = [ f(x+dx/2) - f(x-dx/2) ]/dx  # Returns df/dx at x[1…N]
  20. #   Mean(V) = sum(V)/size(V) # Returns the mean of an array V;
  21. #   Variance(V) = Mean( | V-Mean(V) |^2 ) # Returns the sigma^2 of an array V;
  22. #   StandardDeviation(V) = sqrt(Mean(|V|^2) - |Mean(V)|^2) #Returns standard deviation of an array V;
  23. #   Gaussian(x,x0,sigma)=1/sqrt(2πsigma^2) exp(-0.5{(x-x0)/sigma}^2);
  24. #   Log(x) = ln(x)/ln(10) # log base 10 of x.;
  25. #    function LogGrid(min, max, N) # Makes an N point logarithmic grid.
  26. #
  27. #   Sigma(x) = (1 + Sign(x+1e-16))/2 # is 1 for x=>0, 0 for x<0.  
  28. #   aTan2(s,c) = if c>=0 then atan(s/c) else sign(s+1e-18)*π+atan(s/c)# is -π<theta<=π from s=sin(theta), c=cos(theta);
  29. #   FixRoundOff(x) = (x+1)-1 # Returns x rounded off to about 1e-19.;
  30. #  program BeepIfComplex(z) # Beeps if z is complex ;
  31. #  program ConvertToComplex(x) # Converts x to a complex quantity.
  32. #   SetNegativeToZero(A) =  (Sign(A+1e-16) + 1)/2 * A     #Zeros the elements of an array A which are < 0.
  33. #  This text file explains and gives examples of
  34. #  some of the routines in the file All Library Routines, which
  35. #  should be Opened before trying any of these examples.
  36. ####################################
  37.  
  38.  
  39. ##############
  40. #   Integer Arithmetic
  41.  
  42. # Truncate(x) truncates the fractional part of a number.
  43. # Int (a built-in) rounds to the nearest even integer, 
  44. # while 1e-19 is near the smallest SANE number eps such that
  45. # (1+eps)-eps <> 0.
  46.   Truncate(x) = Int(x*(1+1e-19) - .5) # Returns integer <= x.;
  47.  
  48.   FractionalPart(x) = x - Truncate(x)# Returns fractional part of x>0.;
  49.  
  50.   Round(x, DecimalDigits) =  int(x*10^DecimalDigits)/10^DecimalDigits # rounds off x.;
  51.  
  52. # Examples:
  53. Truncate(2.9872)
  54.   2 
  55. FractionalPart(2.9872)
  56.   0.9872 
  57. Round(2.9872, 3)
  58.   2.987 
  59. Round(2.9872, 2)
  60.   2.99 
  61.  
  62.  
  63. # A simpler way to implement Trunc is to use the fact
  64. # that array indeces are truncated. Therefore, if you know
  65. # the range of integers of interest, just define an integer
  66. # array in that range and subscript it with the value you want
  67. # to truncate.  For example, if you only use integers 1…100,
  68.   Trunc[1…100] = 1…100;
  69. # Then Trunc(1.9) = Trunc[1] = 1,  Trunc(2.3) = 2, etc.
  70.  
  71.  
  72. # Mod(a,b) is "a mod b", i.e. the remainder of a/b.
  73.   Mod(a,b) = a - b*Truncate(a/b) # Returns a mod b.;
  74.  
  75.  
  76. # Also using Int, we can test for even/odd.
  77. # IsEven returns 1 if n is even, 0 if odd. 
  78.   function IsEven(n) # Returns 1 if n is even, 0 if odd.
  79. .   begin
  80. .   if n=int(n+0.5) then
  81. .     IsEven=1
  82. .   else
  83. .     IsEven=0
  84. .   end
  85. .   
  86.  
  87.  
  88. ####################################
  89. #   Matrix  and Vector
  90. # Also see the xCOD files for Inverse, Determinant, and Eigens., 
  91. # which have many more matrix routines, and the sample file
  92. # Vetor and Matrix.
  93.  
  94. # Find the length of a one-dimensional vector. ("•" is opt-8, or use the Shortcuts menu.)
  95.  Length(V) = sqrt(V•V) # length of a vector. ;
  96.  
  97. # The angle between two vectors.
  98.  AngleBetween(V,W) = acos( V•W /length(V) /length(W) ) # angle from vector V to W, in radians.;
  99.  
  100. # The three-dimensional cross product.
  101. function Cross3D(X,Y)  # Returns the 3D cross product of two 3D vectors x,y.
  102. .   var Z
  103. .   #  Input:   X,Y[1…3] 3-D vectors
  104. .   #  Output: Cross3D = X cross Y
  105. .   begin
  106. .      if size(x) <> 3 then
  107. .        Cross3D = " ERROR: X must be a 3D vector for Cross3D"
  108. .      else if size(y) <> 3 then
  109. .         Cross3D = " ERROR: Y must be a 3D vector for Cross3D"
  110. .      else
  111. .      begin
  112. .        z[1] = x[2] y[3] - x[3] y[2];
  113. .        z[2] = x[3] y[1] - x[1] y[3];
  114. .        z[3] = x[1] y[2] - x[2] y[1];
  115. .        Cross3D = z
  116. .      end
  117. .    end
  118. .    
  119.  
  120. # The Hermitian is the conjugate transpose of a matrix.
  121.   Hermitian(theMat) = Transpose(theMat†);
  122.  
  123. # This should only be applied to square matrices.
  124.   Commutator(a,b) = a•b - b•a;
  125.  
  126.  function Trace(theMatrix) # Returns the sum of the diagonal elements of a matrix.
  127. .  var d,Answer
  128. .  begin
  129. .      d = dimension(theMatrix)
  130. .      Answer = 0
  131. .      if size(d)<>2 then 
  132. .         Answer = " ERROR: argument to Trace must be a matrix."
  133. .      else if d[1]<>d[2] then
  134. .          Answer = " ERROR: matrix for Trace must be square."
  135. .      else
  136. .         for j=1…d[1] do Answer = Answer + theMatrix[j,j]
  137. .     Trace = Answer
  138. .  end
  139.  
  140.  
  141. ####################################
  142. #   Calculus
  143.  
  144. # All of these are crude but fairly simple, and use only
  145. # NCII's built in programming language. 
  146. #
  147. #  Since the xCOD based routines in the Discrete Calculus file
  148. #  do most of these same task quicker and more accurately, 
  149. #  all but the first of these have been commented out, leaving
  150. #  the rest only for examples of the NCII programming language.
  151.  
  152.  
  153. # The numerical derivative of a function f(x), returned
  154. #  at the values of the array x. dx is any "small" number.
  155.   Differentiate(f,x,dx) = [ f(x+dx/2) - f(x-dx/2) ]/dx  # Returns df/dx at x[1…N]
  156. # For example, 
  157.   f(x) = sin(x);  x =0…2π@.01;  dsin = DifferentiateFunc(f,x,1e-6)
  158.  
  159. # # This one returns an array. x should be monotomic with y=f(x).
  160. # function DifferentiateArray(y,x)
  161. # .   var y0, y1, n0, n, DA,DA0,DA1, ans
  162. # .   begin
  163. # .     n = size(y);  n0 = FirstIndex(y); nN=n0+n-1;
  164. # .     y0 = y[n0…(nN-1)];  y1 = y[(n0+1)…nN];
  165. # .     DA = (y1-y0)/(x[2]-x[1]);  # derivs at in-between points.
  166. # .     DA0 = DA[1…nN-2]; DA1=DA[2…nN-1];    
  167. # .     ans = y;
  168. # .     ans[(n0+1)…(nN-1)] = (DA0+DA1)/2;  # interpolate middle pts
  169. # .     ans[n0] = (3 DA0[1] - DA0[2])/2;        # extrapolate start
  170. # .     ans[nN] = (3 DA1[nN-2] - DA1[nN-3])/2;  # extrapolate end.
  171. # .     DifferentiateArray = ans
  172. # .   end
  173. # .   
  174.  
  175. # # This assumes that y and x are arrays with y=f(x) and that
  176. # # x is monotomic. Simple trapezoidal integration is done.
  177. # function IntegrateArray(y,x) = sum(y) *(x[2]-x[1]);
  178. # .   var n0, nN, ans
  179. # .   begin
  180. # .     n0 = FirstIndex(y);
  181. # .     nN = n0 + Size(y)-1;
  182. # .     ans = sum(y) - { y[n0]+y[nN] }/2
  183. # .     ans = ans*{ x[2] - x[1] }
  184. # .     IntegrateArray = ans
  185. # .   end
  186. # .   
  187.  
  188. # function Integrate(F,from,to);
  189. # .   var x,dx,y
  190. # .   begin
  191. # .     dx = (to-from)/300;   # we'll do the integral with 300 points.
  192. # .     x = from…to@dx;
  193. # .     y = F(x);
  194. # .     IntegrateFunc = IntegrateArray(y,x)
  195. # .   end
  196. # .   
  197.  
  198. # # Finally an indefinite integral. Both y and x are arrays,
  199. # # y=f(x) and x is monotomic.
  200. # # Because of the FOR loop, this one is slow.
  201. # function IndefiniteIntegral(y,x)
  202. # .   var n0,j, ans
  203. # .   begin
  204. # .     n0 = FirstIndex(x)
  205. # .     ans = y # save space for answer
  206. # .     ans[n0] = 0  #  integral with same limits
  207. # .     for j=(n0+1) to n0+size(x)-1 do
  208. # .       ans[j] = IntegrateArray(y[n0…j],x[n0…j])
  209. # .     IndefiniteIntegral = ans
  210. # .   end
  211. # .   
  212. # # Example: 
  213.  #  x = 0…2π@.01; y = sin(x);  IntegralY = IndefiniteIntegral(y,x)
  214. # # Then plotting [x,y] ; [x,IntegralY] will show 
  215. # #  sin(x) and (cos(x)-1).   (The -1 happens because 
  216. # #  the integration is only to within a constant which makes the 
  217. # #  integral 0 at the smallest value of x.)
  218.  
  219.  
  220.  
  221. ####################################
  222. #   Statistics
  223. # Also see the files for Sorting and Mean, as well as
  224. # Special Functions (which has the Error Function and Chi Square probability).
  225.  
  226. # Standard measures of an array of values.
  227.   Mean(V) = sum(V)/size(V) # Returns the mean of an array V;
  228.   Variance(V) = Mean( | V-Mean(V) |^2 ) # Returns the sigma^2 of an array V;
  229.   StandardDeviation(V) = sqrt(Mean(|V|^2) - |Mean(V)|^2) # Returns standard deviation of an array V;
  230.  
  231. # A "bell-curve" with mean x0 and Std. Dev. sigma.
  232.   Gaussian(x,x0,sigma)=1/sqrt(2πsigma^2) exp(-0.5{(x-x0)/sigma}^2);
  233. #
  234. #    Example:
  235. dx=0.01;x = -4…4@dx; y = Gaussian(x,0,1);    # Now plot [x,y] .
  236. #
  237. sum(y) dx        # normalization of gaussian
  238.   0.99993799 
  239. #
  240. sum(y x^2) dx
  241.   0.9988873     # variance of x.
  242.  
  243.  
  244. ####################################
  245. #   Log Utilities
  246.  
  247. # In general, log A base B is ln(a)/ln(b). 
  248. # ("e" is not defined by default, but "e=exp(1)" will define it.)
  249. Log(x) = ln(x)/ln(10) # log base 10 of x.;
  250.  
  251. # This is useful for making an even grid when doing
  252. # log plots.
  253. #
  254.  function LogGrid(min, max, N) # Makes an N point logarithmic grid.
  255. .   var x,dx, logMax, logMin
  256. .    # Input:    
  257. .    #              min = lowest grid value
  258. .    #              max = highest grid value
  259. .    #              N = number of points
  260. .    # Output:  
  261. .    #             LogGrid = [min, min*Z, min*Z*Z, ..., max]
  262. .    #                    (evenly spaced points in a log plot).
  263. .   begin
  264. .     logMin = log(min); logMax = log(max);
  265. .     dx = (logMax - logMin)/(N-1);
  266. .     x = 10^( logMin…logMax @ dx)
  267. .     LogGrid = x
  268. .   end
  269. .   
  270.  
  271.  
  272. ####################################
  273. #   Other
  274.  
  275. # Sigma is sometimes called the "step" function.
  276.   Sigma(x) = (1 + Sign(x+1e-16))/2 # is 1 for x=>0, 0 for x<0. ;
  277. # for example, 
  278. Table( -2:2, Sigma(-2:2) )
  279. # - - - - - - - - - - - - - - - 
  280.    -2                0
  281.    -1                0
  282.    0                  1
  283.    1                  1
  284.    2                  1
  285.  
  286.  
  287. # aTan2 is takes 2 arguments, sin(theta), cos(theta), and returns -π< theta < π.
  288. # This uses an "if" as part of a one line function. A full-fledged function might be
  289. # clearer, but not as much fun.
  290. aTan2(s,c) = if c>=0 then atan(s/c) else sign(s+1e-18)*π+atan(s/c)# is -π<theta<=π from s=sin(theta), c=cos(theta);
  291.  
  292.  
  293.  
  294. # Return 1 if an object exists, 0 if it doesn't.
  295. function Exists(Obj) # Return 1 if Obj exists, 0 if not.
  296. .   begin
  297. .     if Obj=Obj then Exists=1 else Exists=0
  298. .   end
  299. .   
  300.  
  301. # Sometimes useful for setting small numbers due to
  302. # round off errors to zero.  This works for numbers,
  303. # arrays, or matrices. However, if x is complex
  304. # this will only affect the real part; (i+x)-i will do the
  305. # same for the complex part. (And will make it complex
  306. # if it isn't already.)
  307.   FixRoundOff(x) = (x+1)-1 # Returns x rounded off to about 1e-19.;
  308.  
  309. # Usually real to complex conversions are handled 
  310. # automatically; however, it is possible to tell how and object
  311. # is stored.  
  312.  program BeepIfComplex(z) # Beeps if z is complex ;
  313. .   begin
  314. .      if Size(z) <> SizeAsIfReal(z) then beep
  315. .   end
  316. .   
  317.  
  318. # This makes x complex, which means it will 
  319. # take up twice as much space.  Usually this conversion
  320. # is done automatically when needed.  Under some circumstances
  321. # (such as "if x=1") it will be converted back to real 
  322. # automatically if the complex part is zero.
  323.  program ConvertToComplex(x) # Converts x to a complex quantity.
  324. .   begin
  325. .     x  = (x+i)-i
  326. .   end
  327. .   
  328.  
  329. # The Sign function may be used to do the work of an IF on arrays.  
  330. #  Sign(x) is 1 for x>0, 0 for x=0, and -1 for x<0.  
  331. #  On array, it does Sign on each element of the array to produce a new array.
  332. #  This example sets all the elements of an array which are less than zero to zero.
  333.  SetNegativeToZero(A) =  (Sign(A+1e-16) + 1)/2 * A     #Zeros the elements of an array A which are < 0.
  334.  
  335.